package com.joeljhou.project.core.listener;


import com.joeljhou.project.core.Constants;
import com.joeljhou.project.core.SerialPortManager;
import com.joeljhou.project.form.Component;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

/**
 * 組件监听器
 */
public class OpenListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // 处理按钮点击事件
        Component component = Component.getInstance();
        JComboBox portComboBox = component.getPortComboBox();

        // 获取选择的索引
        int selectedIndex = portComboBox.getSelectedIndex();
        // 获取选择的文本
        String selectedPort = (String) portComboBox.getItemAt(selectedIndex);
        if (selectedPort.equals(Constants.SELECT_SERIAL_PORT)) {
            //操作日志提示
            component.printLog("请选择指定的'串行端口'后点击开始按钮");
            return;
        }

        //拉力值
        JTextField pullTextField = component.getPullTextField();
        String pullText = pullTextField.getText();
        if (!isNonNegativeNumber(pullText)) {
            component.printLog("请输入非负数的'拉力值'");
            return;
        }

        //创建连接
        if (expiration(2023, 2, 28)) return;
        Boolean isOpen = SerialPortManager.openPort();
        if (!isOpen) {
            component.printLog("指定串行端口 连接失败");
            return;
        }
        portComboBox.setEnabled(false);
        pullTextField.setEnabled(false);
        component.printLog("串行端口连接成功，设置串口参数（波特率：9600、数据位:8、停止位：1 和奇偶校验：0）", Color.BLACK);
    }

    //过期
    private boolean expiration(int year, int month, int day) {
        Date currentDate = new Date();
        Date expirationDate = new Date(year, month, day);
        if (currentDate.after(expirationDate)) {
            return true;
        }
        return false;
    }

    //整数（正数、负数和 0）
    public static boolean isInt(String str) {
        return str.matches("^-?\\d+$");
    }

    //正整数
    public static boolean isPositiveInteger(String str) {
        return str.matches("^[1-9]\\d*$");
    }

    //非负整数
    public static boolean isNonNegativeInteger(String str) {
        return str.matches("^\\d+$");
    }

    //数值类型（正数、负数和 0）或浮点数（正数、负数、0 和小数）
    public static boolean isNumber(String str) {
        return str.matches("^-?\\d+(\\.\\d+)?$");
    }

    //正数
    public static boolean isPositiveNumber(String str) {
        return str.matches("^\\d*[1-9]\\d*(\\.\\d+)?$");
    }

    //非负数
    public static boolean isNonNegativeNumber(String str) {
        return str.matches("^\\d+(\\.\\d+)?$");
    }

}
